/**
 * Created by dale on 2017/6/22.
 */
$(document).ready(function () {
    var form=$('#form');
    var $form=new xhForm(form);
    $('title')[0].innerHTML='客户基本情况';
    $(".form_datetime").datetimepicker({
                        format: 'yyyy-mm-dd',
                        language: 'zh-CN',
                        minView: "month",
                        autoclose:true, });

    $form.fill($(schoolData)[0]);
    form.initeValidate();
    $('body').click();
    
    $('#style3Tab1').height($(window).height()-100);


    var provinceName=$(schoolData)[0].sProvinceName;
    var cityName=$(schoolData)[0].sCityName;
    var countryName=$(schoolData)[0].sCountyName;

    $('[name=iMarketId]').select2();
    $('[name=iOperateId]').select2();

    //绑定字典内容到指定的Select控件
    function BindSelect(ctrlName, url,area) {
        var control = $('#' + ctrlName);
        //设置Select2的处理
        control.select2({
            placeholder:'请选择',
            templateResult:  function formatRepo(repo){
                return repo.text
            },
            templateSelection: function (repo) {
                if(repo.id!=""){
                    $('#select2-'+ctrlName+'-container').parent().removeClass('warn-color').addClass('success-color');
                }
                return repo.text;
            },
            escapeMarkup: function (m) {
                $('#select2-'+ctrlName+'-container').parent().addClass('warn-color');
                return m;
            }
        });

        //绑定Ajax的内容
        $.getJSON(url, function (data) {
            control.empty();//清空下拉框
            if(area==null){
                control.append("<option value='' style='display: none;' selected>请选择</option>");
                $.each(data, function (id,item) {
                    control.append("<option value='" + item['id'] + "'>" + item['text'] + "</option>");

                });
            }else {

                $.each(data, function (id,item) {
                    if(area['id']==item['id']){
                        control.append("<option value='" + item['id'] + "' selected>" + item['text'] + "</option>");
                    }else {
                        control.append("<option value='" + item['id'] + "'>" + item['text'] + "</option>");
                    }

                });
            }
        });
    }







    if($(schoolData)[0].sProvinceName!=null){

        $.ajax({
            url  :baseUrl+'customer/getAreaBynames',
            type : 'POST',
            async : false,
            data : {'qnames':[provinceName,cityName,countryName]},
            dataType : 'JSON',
            success:function (data) {
                BindSelect('provinceSelect',baseUrl+"customer/getAreaData?pid=0",data[0]);
                BindSelect('citySelect',baseUrl+"customer/getAreaData?pid="+data[0]['id'],data[1]);
                BindSelect('countrySelect',baseUrl+"customer/getAreaData?pid=0"+data[1]['id'],data[2]);

            },
            error:function (result) {
                console.log(result);
            }
        });
    }else {
        BindSelect('provinceSelect',baseUrl+"customer/getAreaData?pid=0",null);
        BindSelect('citySelect',baseUrl+"customer/getAreaData?pid=1",null);
        BindSelect('countrySelect',baseUrl+"customer/getAreaData?pid=1",null);
    }

    $("#provinceSelect").on("change", function (e) {
        var pid = $("#provinceSelect").val();
        $("#citySelect").val("").trigger('change');
        $("#countrySelect").val("").trigger('change');
        if(pid!=''){
            BindSelect("citySelect", baseUrl+"customer/getAreaData?pid="+pid);
        }
    });

    $("#citySelect").on("change", function (e) {
        var pid = $("#citySelect").val();
        $("#countrySelect").val("").trigger('change');
        if(pid!=''){
            BindSelect("countrySelect", baseUrl+"customer/getAreaData?pid="+pid);
        }
    });



    $('#save').click(function () {
        var commitData=$('#form').serialize();
        var str=decodeURI(commitData);
        // console.log($('[name$="tSchoolDate"]').val());
        if($('#provinceSelect').select2('data')[0]==undefined){
            // alert('请选择省');
            window.top.swal({
                title:'省未选择',
                text:'请你选择省',
                timer:700,
                showConfirmButton:false,

            });

            return false;
        }else if($('#citySelect').select2('data')[0]==undefined){
            // alert('请选择市');
            window.top.swal({
                title:'市未选择',
                text:'请选择市',
                timer:700,
                showConfirmButton:false,
            });
            return false;
        }else if($('#countrySelect').select2('data')[0]==undefined){
            // alert('请选择区');
            window.top.swal({
                title:'区未选择',
                text:'请选择区',
                timer:700,
                showConfirmButton:false,

            });
            return false;
        }else if($('[name$="tSchoolDate"]').val()==''){
            window.top.swal({
                title:'办校时间未选择',
                text:'请选择办校时间',
                timer:700,
                showConfirmButton:false,

            });
            return false;
        }
        // try{
            str= str.replace($('#provinceSelect ').select2('data')[0].id,$('#provinceSelect ').select2('data')[0].text);
            str= str.replace($('#citySelect ').select2('data')[0].id,$('#citySelect ').select2('data')[0].text);
            str=str.replace($('#countrySelect ').select2('data')[0].id,$('#countrySelect ').select2('data')[0].text);
        // }catch (e){
        //    
        // }finally {
            str=encodeURI(str);
           // console.log(str);
            $.ajax({
                url  :baseUrl+'customer/saveCustomerInfo',
                type : 'POST',
                data : str,
                dataType : 'JSON',
                success:function (data) {
                    window.top.swal({
                        title:'修改成功',
                        text:'学校信息已成功修改',
                        timer:700,
                        showConfirmButton:false
                    });
                    window.location.reload();
                },
                error:function (result) {
                    window.top.xhTop.showError('错误',result.responseJSON.error);
                    xhExtra.setBtnNormal($('#save'));
                }
            
            });
        // }
    });
    
    //返回 
    $('.return').click(function () {
        $('#xhGrade', window.parent.document).show();
        $('#customerTab', window.parent.document).hide();

    });


});